<?php

namespace App\Repositories;

use App\Models\Goods;
use App\Models\Order;
use App\Models\Statistics;
use App\User;
use InfyOm\Generator\Common\BaseRepository;

/**
 * Class StatisticsRepository
 * @package App\Repositories
 * @version October 9, 2017, 11:05 am CST
 *
 * @method Statistics findWithoutFail($id, $columns = ['*'])
 * @method Statistics find($id, $columns = ['*'])
 * @method Statistics first($columns = ['*'])
*/
class StatisticsRepository extends BaseRepository
{
    /**
     * @var array
     */
    protected $fieldSearchable = [
        'type',
        'add_users_count',
        'users_count',
        'goods_count',
        'orders_count',
        'orders_add_count',
        'orders_add_pay_count',
        'orders_return_count',
        'orders_return_amount',
        'orders_return_rate',
        'repurchase_count',
        'repurchase_rate',
        'orders_price_amount',
        'orders_pay_money_amount'
    ];

    /**
     * Configure the Model
     **/
    public function model()
    {
        return Statistics::class;
    }

    public function generate($day=1,$type=1,$date=null)
    {
        if(!$date){
            $date = date('Y-m-d');
        }
        if($type==3){
            $end_date = date('Y-m-01 17:00:01', strtotime($date));
        }else{
            $end_date = date('Y-m-d 17:00:01', strtotime($date));
        }
        if($type==3){
            $start_date = date('Y-m-01 17:00:01',strtotime($end_date)-3600*24*3);
        }else{
            $start_date = date('Y-m-d H:i:s',strtotime($end_date)-3600*24*$day);
        }
        $orders = Order::where('created_at','<',$end_date)->where('created_at','>=',$start_date)->get();
        $orders->load('user');
        $add_users_count = User::where('created_at','<',$end_date)
            ->where('created_at','>=',$start_date)->count();
        $goods_count = Goods::where('status',1)->count();
        $users_count = User::count();
        $orders_count= Order::count();

        $repurchase_count = 0;
        $orders_add_count = 0;
        $orders_add_pay_count = 0;
        $orders_return_count = 0;
        $orders_return_amount = 0;
        $orders_price_amount = 0;
        $orders_pay_money_amount = 0;
        $repurchase_ids_arr = [];
        $_old_user_ids = Order::where('created_at','<',$start_date)
            ->where('pay_status',1)->groupBy('user_id')->pluck('user_id');
//        dd($_old_user_ids);
        $users_rank = [];
        $goods_rank = [];
        $users_ids = [];
        $goods_ids = [];
        $attributes_ids = [];

        $orders->load('goods');
        $orders->load('user');
        foreach ($orders as $order) {
            $orders_add_count++;
            if($order->pay_status==1){
                $users_ids[] = $order->user_id;
                $orders_add_pay_count++;
                $orders_price_amount += $order->price;
                $orders_pay_money_amount += $order->pay_money;

                if(isset($users_rank[$order->user_id])) {
                    $users_rank[$order->user_id]['order_money'] += $order->price;
                    $users_rank[$order->user_id]['pay_money'] += $order->pay_money;
                    $users_rank[$order->user_id]['order_num'] += 1;
                    if($order->status==12)
                        $users_rank[$order->user_id]['order_return_num'] += 1;
                    $users_rank[$order->user_id]['return_money'] += $order->pay_money - $order->calculate_pay_price;
                }else{
                    $_user = [];
                    $_user['user_id'] = $order->user->id;
                    if($order->status==12)
                        $_user['order_return_num'] = 1;
                    else
                        $_user['order_return_num'] = 0;
                    $_user['order_num'] = 1;
                    $_user['order_money'] = $order->price;
                    $_user['pay_money'] = $order->pay_money;
                    $_user['return_money'] = $order->pay_money - $order->calculate_pay_price;
                    $users_rank[$order->user_id] = $_user;
                }
                foreach ($order->goods as $v) {
                    if($v->attribute_id){
                        $goods_ids[] = $v->goods_id;
                        $attributes_ids[] = $v->attribute_id;
                        $_key = 'attribute_'.$v->attribute_id.'_'.$v->price;
                        $_data = [
                            'type'=>'attribute',
                            'price'=>$v->price,
                            'goods_id'=>$v->goods_id,
                            'attribute_id'=>$v->attribute_id,
                            'number'=>$v->number,
                            'return_number'=>$v->return_number,
                        ];
                    }else{
                        $goods_ids[] = $v->goods_id;
                        $_key = 'goods_'.$v->goods_id.'_'.$v->price;
                        $_data = [
                            'type'=>'goods',
                            'price'=>$v->price,
                            'goods_id'=>$v->goods_id,
                            'attribute_id'=>0,
                            'number'=>$v->number,
                            'return_number'=>$v->return_number,
                        ];
                    }
                    if(isset($goods_rank[$_key])){
                        $goods_rank[$_key]['number'] += $v->number;
                        $goods_rank[$_key]['return_number'] += $v->return_number;
                    }else{
                        $goods_rank[$_key] = $_data;
                    }
                }

                if($order->status==12){
                    $orders_return_amount += $order->pay_money - $order->calculate_pay_price;
                    $orders_return_count++;
                }

                if($_old_user_ids->search($order->user_id)!==false){
                    if(!$order->user){
//                    dd($order);
                        continue;
                    }
                    if(!in_array($order->user->id, $repurchase_ids_arr)){
                        $repurchase_ids_arr[] = $order->user->id;
                        $repurchase_count++;
                    }
                }else{
                    $_old_user_ids->push($order->user_id);
                }
            }
        }
        $_repurchase_30_num = 0;
        $_old_user_ids = Order::where('created_at','<',date('Y-m-d 17:00:01', strtotime($date))-3600*24*30)->where('pay_status',1)->groupBy('user_id')->pluck('user_id');
        $_30_orders = Order::where('created_at','<',date('Y-m-d 17:00:01', strtotime($date)))->where('created_at','>=',date('Y-m-d 17:00:01',strtotime($date))-3600*24*30)->where('pay_status',1)->get();
        $repurchase_ids_arr_30 = [];
        foreach ($_30_orders as $order) {
            if($_old_user_ids->search($order->user_id)!==false){

                if(!$order->user){
//                    dd($order);
                    continue;
                }
                if(!in_array($order->user_id, $repurchase_ids_arr_30)){
                    $repurchase_ids_arr_30[] = $order->user_id;
                    $_repurchase_30_num++;
                }
            }else{
                $_old_user_ids->push($order->user_id);
            }
        }
//        dump($_repurchase_30_num);
//        dump(Order::where('created_at','<',date('Y-m-d 17:00:01'))->where('created_at','>=',date('Y-m-d 17:00:01')-3600*24*30)->where('pay_status',1)->count());

        $repurchase_rate = sprintf("%7.2f",$_repurchase_30_num/(Order::where('created_at','<',date('Y-m-d 17:00:01',strtotime($date)))->where('created_at','>=',date('Y-m-d 17:00:01',strtotime($date))-3600*24*30)->where('pay_status',1)->pluck('user_id')->unique()->count()));

        $orders_return_rate = sprintf("%7.2f", $orders_return_count/$orders_add_pay_count);
        $goods_rank = collect($goods_rank);
        $users_rank = collect($users_rank);
        $_data = [
            'type'=>$type,
            'date'=>$date,
            'add_users_count'=>$add_users_count,
            'users_count'=>$users_count,
            'goods_count'=>$goods_count,
            'orders_count'=>$orders_count,
            'orders_add_count'=>$orders_add_count,
            'orders_add_pay_count'=>$orders_add_pay_count,
            'orders_return_count'=>$orders_return_count,
            'orders_return_amount'=>$orders_return_amount,
            'orders_return_rate'=>$orders_return_rate,
            'repurchase_count'=>$repurchase_count,
            'repurchase_rate'=>$repurchase_rate,
            'orders_price_amount'=>$orders_price_amount,
            'orders_pay_money_amount'=>$orders_pay_money_amount,
            'json'=>json_encode(['goods_rank'=>$goods_rank->sortByDesc('order_num'),
                'users_ids'=>$users_ids,'goods_ids'=>$goods_ids,'attributes_ids'=>$attributes_ids],256),
            'json2'=>json_encode($users_rank->sortByDesc('order_num'),256),
        ];
        $_old = Statistics::where('type', $_data['type'])->where('date',$_data['date'])->first();
        if($_old){
            if(date('Y-m-d')!=$date){
                unset($_data['users_count']);
                unset($_data['goods_count']);
                unset($_data['orders_count']);
            }
            $_old->update($_data);
        }else{
            Statistics::create($_data);
        }
    }

    public function distributionStatistics($type=1,$user_id=0)
    {
        $start_date = null;
        $end_date = null;
        if($type==1){
            $start_date = date('Y-m-d 00:00:00');
            $end_date = date('Y-m-d 00:00:00',time()+3600*24);
        }elseif($type==2){
            $start_date = date('Y-m-01 00:00:00');
            $end_date = date('Y-m-d 00:00:00',time()+3600*24);
        }
        $pairing_num = Order::where('pairing_id',$user_id)->where('pairing_at','>=',$start_date)->where('pairing_at','<=',$end_date)->count();
        $verify_num = Order::where('verifier_id',$user_id)->where('verify_at','>=',$start_date)->where('verify_at','<=',$end_date)->count();
        $shipping_num = Order::where('courier_id',$user_id)->where('real_shipping_at','>=',$start_date)->where('real_shipping_at','<=',$end_date)->count();
        return [
            'pairing_num'=>$pairing_num,
            'verify_num'=>$verify_num,
            'shipping_num'=>$shipping_num,
        ];
    }
}
